package com.candy.candyoauth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.sql.DataSource;

/**
 * @author Fox
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //  password模式
        // http://localhost:8088/oauth/token?username=fox&password=123123&grant_type=password&client_id=gateway-server&client_secret=123123&scope=read
        // http://localhost:8088/oauth/token?grant_type=refresh_token&client_id=gateway-server&client_secret=123123&refresh_token=070b0f65-8026-4d8a-9786-3f11ab30d48e
        // http://localhost:8088/oauth/check_token?token=7f660d89-a495-4c16-8c8a-1b7dbb7748a9

        clients
                .withClientDetails(clientDetails());
//        clients.authorizedGrantTypes("authorization_code, refresh_token, password");
//        clients.inMemory()
//                .withClient("client")
//                .authorizedGrantTypes("authorization_code, refresh_token, password")
//                .authorities("ROLE_CLIENT")
//                .secret(passwordEncoder.encode("123123"))
//                .scopes("read", "write")
//                .resourceIds("RESOURCE_ID")
//                .redirectUris("https://www.baidu.com/");
    }

    @Bean
    public ClientDetailsService clientDetails() {
        // 读取oauth_client_details表 使用jdbc存储客户端信息
        return new JdbcClientDetailsService(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager) //使用密码模式需要配置  指定认证管理器
                .tokenStore(tokenStore)  //指定token存储到redis
                .reuseRefreshTokens(true)  //refresh_token是否重复使用
                .userDetailsService(userDetailsService) //刷新令牌授权包含对用户信息的检查
                // .setSupportRefreshToken()
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); //支持GET,POST请求
        // 配置tokenServices参数
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(endpoints.getTokenStore());
        tokenServices.setSupportRefreshToken(true);//允许支持刷新token
        tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
        tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
        tokenServices.setAccessTokenValiditySeconds(60); // accessToken有效时间：60秒
        tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 30);//refreshToken有效时间：30天
        tokenServices.setReuseRefreshToken(true);
        endpoints.tokenServices(tokenServices);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //允许表单认证
        security.allowFormAuthenticationForClients()
                // 配置校验token需要带入clientId 和clientSeret配置
                .checkTokenAccess("isAuthenticated()")
                .checkTokenAccess("permitAll()")

        ;
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        System.out.println(bCryptPasswordEncoder.encode("123123"));
    }

}
